﻿Imports TBCC.UtilityMobile
Imports System.Drawing
Imports System.Drawing.Image
Imports System.Text
Imports System.ComponentModel
Imports System.Windows.Forms

Public Class RealTimeDataCar


    Private Sub RealTimeDataCar_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'LoadProjectList()
        'FormatDataGridView()
        Me.Timer1.Start()
        Me.bgLoad.WorkerSupportsCancellation = True
        If Not Me.bgLoad.IsBusy Then
            Me.bgLoad.RunWorkerAsync()
        End If
    End Sub




    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        ' isUpdateFormStatus = True
        Me.Close()

    End Sub

    ''' <summary>
    ''' 为DataGridView添加行号
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub dgvRealDataCar_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgvRealDataCar.RowPostPaint
        Dim brush As System.Drawing.Brush = New SolidBrush(dgvRealDataCar.RowHeadersDefaultCellStyle.ForeColor)
        e.Graphics.DrawString((e.RowIndex + 1).ToString(), dgvRealDataCar.DefaultCellStyle.Font, Brush, e.RowBounds.Location.X + 12, e.RowBounds.Y + 5)

    End Sub

    Private Sub TimerRealDataCar_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerRealDataCar.Tick
        'LoadProjectList()
        'FormatDataGridView()
        If Not Me.bgLoad.IsBusy Then
            Me.bgLoad.RunWorkerAsync()
        End If
    End Sub

    ''' <summary>
    ''' 窗体关闭时释放资源
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub RealTimeDataCar_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Me.TimerRealDataCar.Stop()
        If Me.bgLoad.IsBusy Then
            Me.bgLoad.CancelAsync()
        End If
        System.GC.Collect()

    End Sub
    Private Sub LoadProjectList()

        Dim carList As IList(Of ProjectInfo.CarProjectInfo)
        carList = CarProjectService.GetAllCarProjectInfo()
        Dim CarWebServiceAd As String = KeyValuePairClass.GetValue1("CarWebServiceAdd")
        If CarWebServiceAd.Length <= 0 Then
            msg.Show("请配置数据下载地址！")
            Exit Sub
        End If
        Dim WebList As IList(Of ProjectInfo.CarHDItem)
        WebList = New List(Of ProjectInfo.CarHDItem)
        Dim webCar As New CarWebServiceAdd.AllService
        webCar.Url = String.Format("http://{0}/ccdccservice/services/AllService", CarWebServiceAd)
        Try
            For Each car As ProjectInfo.CarProjectInfo In carList
                Dim c As ProjectInfo.CarHDItem = New ProjectInfo.CarHDItem
                Dim realCar As New CarWebServiceAdd.CarRealView_new
                realCar = webCar.getCarRealData_sy(car.AuthCode, car.ProId)


                Select Case CInt(realCar.flag)
                    Case 0   '服务器错误

                        msg.ShowError("远程服务器发生错误！")
                        Exit For
                    Case 1   '项目中未包含该项目或者鉴权不对


                        msg.Show(String.Format("车载{0}服务器中未配置或配置的鉴权不对！", car.CarProjectName))
                        Continue For

                    Case 2    '调用返回正常
                        c.ProjectName = car.CarProjectName

                        c.AuthCode = car.AuthCode
                        c.ProId = car.ProId

                        If car.CarProjectType = 1 Then
                            c.ProjectType = "移动车载"
                        Else
                            c.ProjectType = "移动小批零"
                        End If

                        If realCar.ai1.ToString = "" Then
                            c.AI1 = "---"
                        Else
                            c.AI1 = realCar.ai1
                        End If

                        If realCar.ai2.ToString = "" Then
                            c.AI2 = "---"
                        Else
                            c.AI2 = realCar.ai2
                        End If

                        If realCar.ai3.ToString = "" Then
                            c.AI3 = "---"
                        Else
                            c.AI3 = realCar.ai3
                        End If

                        If realCar.ai4.ToString = "" Then
                            c.AI4 = "---"
                        Else
                            c.AI4 = realCar.ai4
                        End If

                        If realCar.latitude_dir.ToString <> "" Then
                            c.Latitude_dir = realCar.latitude_dir
                        Else

                            c.Latitude_dir = -1
                        End If

                        If realCar.latitude.ToString = "" Then
                            c.Latitude = "---"
                        Else
                            c.Latitude = ConvertLa(realCar.latitude.ToString, c.Latitude_dir)

                        End If



                        If realCar.longitude_dir.ToString <> "" Then
                            c.Longitude_dir = realCar.longitude_dir
                        Else
                            c.Longitude_dir = -1

                        End If

                        If realCar.longitude.ToString <> "" Then
                            c.Longitude = ConvertLo(realCar.longitude.ToString, c.Longitude_dir)
                        Else
                            c.Longitude = "---"

                        End If


                        c.UpdateTime = realCar.updateTime
                       



                        If realCar.runStatus.ToString = "" Then
                            c.RunStatus = "---"
                        ElseIf realCar.runStatus.ToString.Equals("1") Then
                            c.RunStatus = "停止"
                        ElseIf realCar.runStatus.ToString.Equals("2") Then
                            c.RunStatus = "运行"
                        Else
                            c.RunStatus = "---"
                        End If


                        If realCar.alarmStatus.ToString = "" Then
                            c.AlarmStatus = "---"
                        ElseIf CInt(realCar.alarmStatus) = 1 Then
                            c.AlarmStatus = "报警"
                        ElseIf CInt(realCar.alarmStatus) = 2 Then
                            c.AlarmStatus = "正常"
                        ElseIf CInt(realCar.alarmStatus) = 0 Then
                            c.AlarmStatus = "预警"
                        Else
                            c.AlarmStatus = "---"

                        End If



                        Dim str As String = ""
                        If CInt(realCar.speedStatus) = 0 Then
                            str = "↑"
                        Else
                            str = ""
                        End If
                        If realCar.carSpeed.ToString <> -300 Then

                            c.CarSpeedValue = realCar.carSpeed.ToString + "km/h" + str
                        Else
                            c.CarSpeedValue = "---"
                        End If

                        If CInt(realCar.unloadStatus) = 0 Then
                            c.TransportState = "卸货"
                        ElseIf CInt(realCar.unloadStatus) = 1 Then
                            c.TransportState = "运输"
                        Else
                            c.TransportState = "---"
                        End If


                        Dim stralarm As String
                        Dim alarmsta As String
                        stralarm = Convert.ToString(CInt(realCar.alarmData), 2).ToString() 'realCar.alarmData.ToString

                        For i As Integer = 0 To stralarm.Length - 1

                            If stralarm.Chars(stralarm.Length - i - 1) = "0" Then
                                If i Mod 2 = 0 Then

                                    alarmsta = "↑"


                                Else

                                    alarmsta = "↓"


                                End If
                            Else

                                alarmsta = ""

                            End If

                            If i = 0 OrElse i = 1 Then
                                c.AI1 = c.AI1 + alarmsta
                                Continue For

                            End If

                            If i = 2 OrElse i = 3 Then
                                c.AI2 = c.AI2 + alarmsta
                                Continue For
                            End If


                            If i = 4 OrElse i = 5 Then
                                c.AI3 = c.AI3 + alarmsta
                                Continue For
                            End If


                        Next

                        If realCar.connectionStatus.ToString = "" Then

                            c.ConnectionStatus = "---"
                        ElseIf realCar.connectionStatus.ToString.Equals("2") Then
                            c.ConnectionStatus = "连接"
                        Else
                            c.ConnectionStatus = "断开"
                            c.AI1 = "---"
                            c.AI2 = "---"
                            c.AI3 = "---"
                            c.AI4 = "---"
                            c.Latitude = "---"
                            c.Longitude = "---"
                            c.RunStatus = "---"
                            c.AlarmStatus = "---"
                            c.TransportState = "---"
                            c.CarSpeedValue = "---"
                        End If




                        WebList.Add(c)

                    Case Else

                        Continue For
                End Select


                'If CInt(realCar.flag) <> 2 Then
                '    Continue For
                'End If


            Next

        Catch ex As Exception
            Debug.Print("realtime webservice  failed: %s\n ", ex.Message())
            msg.ShowWarning(String.Format("无法读取实时数据！", ex.Message()))
            Exit Sub


        End Try
        
        ShowData(WebList)

    End Sub

    Private Delegate Sub DShowData(ByVal data As IList(Of ProjectInfo.CarHDItem))

    Private Sub ShowData(ByVal data As IList(Of ProjectInfo.CarHDItem))
        If Me.InvokeRequired Then
            Me.Invoke(New DShowData(AddressOf _ShowData), data)
        Else
            _ShowData(data)
        End If
    End Sub

    Private Sub _ShowData(ByVal data As IList(Of ProjectInfo.CarHDItem))
        Me.dgvRealDataCar.DataSource = data
    End Sub

    Private Function ConvertLa(ByVal latitude As String, ByVal dir As Integer) As String
        Dim count As Integer = latitude.ToString.Length
        Dim str As String
        If dir = 1 Then
            str = "'N"
        ElseIf dir = 0 Then
            str = "'S"
        Else
            str = ""
        End If

        If count > 0 Then
            'msg.Show("latitude.IndexOf('.')=" + latitude.IndexOf(".").ToString)

            Dim start As String = Nothing


            If latitude.IndexOf(".") = -1 Then
                start = latitude.Substring(0, latitude.Length) '找到这一点
            Else
                start = latitude.Substring(0, latitude.IndexOf(".")) '找到这一点

            End If

            If start.Equals("-300") Or start.Equals("-300.00") Then
                latitude = "---"
                'Exit For

            Else

                Dim first As String = ""
                If start.Length > 0 Then

                    If start.Length >= 2 Then
                        If start.Length = 2 Then
                            first = start.Substring(0, start.Length - 2) + "00°"
                        Else
                            first = start.Substring(0, start.Length - 2) + "°"

                        End If
                        Dim secoud As String = start.Substring(start.Length - 2)
                        'msg.Show("latitude.IndexOf('.')=" + latitude.IndexOf(".").ToString)
                        'msg.Show("count=" + count.ToString)
                        Dim endString As String
                        If latitude.IndexOf(".") > 0 Then
                            endString = latitude.Substring(latitude.IndexOf("."))
                        Else

                            endString = ""
                        End If

                        latitude = first + secoud + endString + str
                    Else
                        latitude = start + "°00.00" + str
                    End If



                Else
                    latitude = "---"

                End If
            End If


        Else
            latitude = "---"

        End If
        Return latitude
    End Function

    Private Function ConvertLo(ByVal longitude As String, ByVal dir As Integer) As String
        Dim countL As Integer = longitude.ToString.Length

        Dim str As String
        If dir = 0 Then
            str = "'E"
        ElseIf dir = 1 Then
            str = "'W"
        Else
            str = ""
        End If

        If countL > 0 Then
            Dim start As String = Nothing


            If longitude.IndexOf(".") = -1 Then
                start = longitude.Substring(0, longitude.Length) '找到这一点
            Else
                start = longitude.Substring(0, longitude.IndexOf(".")) '找到这一点

            End If


            If start.Equals("-300") Or start.Equals("-300.00") Then
                longitude = "---"

            Else

                Dim first As String = ""
                If start.Length > 0 Then

                    If start.Length >= 2 Then
                        If start.Length = 2 Then
                            first = start.Substring(0, start.Length - 2) + "00°"
                        Else
                            first = start.Substring(0, start.Length - 2) + "°"

                        End If
                        Dim secoud As String = start.Substring(start.Length - 2)


                        Dim endString As String
                        If longitude.IndexOf(".") > 0 Then
                            endString = longitude.Substring(longitude.IndexOf("."))
                        Else
                            endString = ""

                        End If

                        longitude = first + secoud + endString + str
                    Else
                        longitude = start + "°00.00" + str
                    End If



                Else
                    longitude = "---"

                End If

            End If
        Else
            longitude = "---"

        End If
        Return longitude
    End Function

    Public Sub GetDataGridViewISNull()
        Dim count As Integer = Me.dgvRealDataCar.Rows.Count

        If count <= 0 Then
            msg.Show("你查询的范围内没有数据,请重置！")
        End If

    End Sub



    Private Sub dgvRealDataCar_Sorted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvRealDataCar.Sorted
        For i As Integer = 0 To Me.dgvRealDataCar.Rows.Count - 1
            For j As Integer = 1 To Me.dgvRealDataCar.Columns.Count - 1
                If Me.dgvRealDataCar.Rows(i).Cells(j).Value = "报警" Then
                    Me.dgvRealDataCar.Rows(i).Cells(j).Style.ForeColor = Color.Red
                End If
            Next
        Next
    End Sub

    ''' <summary>
    ''' 格式化关键字
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub dgvRealDataCar_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles dgvRealDataCar.DataBindingComplete
        Try
            dgvRealDataCar.Columns("ProjectType").DisplayIndex = 1
            dgvRealDataCar.Columns("ProjectName").DisplayIndex = 2
            dgvRealDataCar.Columns("carspeed").DisplayIndex = 3
            dgvRealDataCar.Columns("AlarmStatus").DisplayIndex = 4
            dgvRealDataCar.Columns("TransportState").DisplayIndex = 5
            dgvRealDataCar.Columns("RunStatus").DisplayIndex = 6
            dgvRealDataCar.Columns("ConnectStatus").DisplayIndex = 7
            dgvRealDataCar.Columns("Latitude").DisplayIndex = 8
            dgvRealDataCar.Columns("Latitude").Width = 100
            dgvRealDataCar.Columns("Longitude").DisplayIndex = 9
            dgvRealDataCar.Columns("Longitude").Width = 100
            dgvRealDataCar.Columns("AI1").DisplayIndex = 10
            dgvRealDataCar.Columns("AI2").DisplayIndex = 11
            dgvRealDataCar.Columns("AI3").DisplayIndex = 12
            'dgvRealDataCar.Columns("AI3").ValueType = dgvRealDataCar.Columns("RunStatus").ValueType
            dgvRealDataCar.Columns("AI4").DisplayIndex = 13
            dgvRealDataCar.ClearSelection()
        Catch ex As Exception

        End Try
    End Sub

    Public Sub FormatDataGridView()
        For i As Integer = 0 To dgvRealDataCar.RowCount - 1
            For j As Integer = 0 To dgvRealDataCar.ColumnCount - 1
                Dim AlarmStatus As String = dgvRealDataCar.Rows(i).Cells("AlarmStatus").Value

                If AlarmStatus.Equals("2") Or AlarmStatus.Equals("正常") Then
                    dgvRealDataCar.Rows(i).Cells("AlarmStatus").Value = "正常"
                ElseIf AlarmStatus.Equals("1") Or AlarmStatus.Equals("报警") Then
                    dgvRealDataCar.Rows(i).Cells("AlarmStatus").Value = "报警"
                    Dim cell As DataGridViewCell = Me.dgvRealDataCar.Rows(i).Cells("AlarmStatus") '获取这列
                    cell.Style.ForeColor = Color.Red '设置红色
                ElseIf AlarmStatus.Equals("0") Or AlarmStatus.Equals("预警") Then
                    dgvRealDataCar.Rows(i).Cells("AlarmStatus").Value = "预警"
                    Dim cell As DataGridViewCell = Me.dgvRealDataCar.Rows(i).Cells("AlarmStatus") '获取这列
                    cell.Style.ForeColor = Color.Orange

                Else
                    dgvRealDataCar.Rows(i).Cells("AlarmStatus").Value = "---"
                End If

                Dim a1 As String = dgvRealDataCar.Rows(i).Cells("AI1").Value
                If a1.Equals("-300.00") Or a1.Equals("-300") Then
                    dgvRealDataCar.Rows(i).Cells("AI1").Value = "---"

                End If

                If a1.Contains("↑") OrElse a1.Contains("↓") Then
                    dgvRealDataCar.Rows(i).Cells("AI1").Style.ForeColor = Color.Red '设置红色
                End If
                Dim a2 As String = dgvRealDataCar.Rows(i).Cells("AI2").Value
                If a2.Equals("-300.00") Or a2.Equals("-300") Then
                    dgvRealDataCar.Rows(i).Cells("AI2").Value = "---"

                End If
                If a2.Contains("↑") OrElse a2.Contains("↓") Then
                    dgvRealDataCar.Rows(i).Cells("AI2").Style.ForeColor = Color.Red '设置红色
                End If

                Dim a3 As String = dgvRealDataCar.Rows(i).Cells("AI3").Value
                If a3.Equals("-300.00") Or a3.Equals("-300") Then
                    dgvRealDataCar.Rows(i).Cells("AI3").Value = "---"

                End If
                If a3.Contains("↑") OrElse a3.Contains("↓") Then
                    dgvRealDataCar.Rows(i).Cells("AI3").Style.ForeColor = Color.Red '设置红色
                End If
                Dim a4 As String = dgvRealDataCar.Rows(i).Cells("AI4").Value

                'System.Diagnostics.Debug.WriteLine(dgvRealDataCar.Rows(i).Cells("AI4").ValueType.ToString)
                If a4.Equals("-300") Or a4.Equals("-300.00") Then
                    dgvRealDataCar.Rows(i).Cells("AI4").Value = "---"
                End If
                If a4.Contains("↑") OrElse a4.Contains("↓") Then
                    dgvRealDataCar.Rows(i).Cells("AI4").Style.ForeColor = Color.Red '设置红色
                End If

                '车速是否为超速，超速显示红色
                Dim CarSpeed As String = dgvRealDataCar.Rows(i).Cells("carspeed").Value
                If CarSpeed.Contains("↑") Then
                    dgvRealDataCar.Rows(i).Cells("carspeed").Style.ForeColor = Color.Red '设置红色
                End If


                Dim TransportState As String = dgvRealDataCar.Rows(i).Cells("TransportState").Value
                If TransportState.Contains("卸货") Then
                    dgvRealDataCar.Rows(i).Cells("TransportState").Style.ForeColor = Color.Green
                End If




            Next
        Next
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Timer1.Stop()
    End Sub

    Private Sub bgLoad_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgLoad.DoWork
        LoadProjectList()
        FormatDataGridView()
    End Sub

    Private Sub dgvRealDataCar_CellMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvRealDataCar.CellMouseDoubleClick
        If Me.dgvRealDataCar.SelectedRows.Count = 1 Then
            Dim Pid As String = Me.dgvRealDataCar.SelectedRows(0).Cells("ProjectID").Value
            Dim ACode As String = Me.dgvRealDataCar.SelectedRows(0).Cells("AuthCode").Value
            Dim Addr As String = String.Format("http://www.thermoberg.com/ccdcc/map/customer_realmap.jsp?projectId={0}&code={1}", Pid, ACode)
            ' Dim url As New Uri()
            Debug.WriteLine(Addr)

            Dim url As New Uri(Addr)

            Dim frm As New Map(url)
            frm.ShowDialog()
        End If
    End Sub

    Private Sub dgvRealDataCar_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvRealDataCar.CellContentClick

    End Sub
End Class